<?php

// $Id: subjectmanagement.php, 2010/10/06 afterlastangel Exp $

/**
 * This page lists all the instances of studentcp in a particular course
 *
 * @author  Le Kien Truc <afterlastangel@gmail.com>
 * @version $Id: subjectupdate.php, 2010/10/06 $
 * @package mod/studentcp
 */
require_once(dirname(dirname(dirname(__FILE__))) . '/../config.php');
require_once(dirname(__FILE__) . '/../locallib.php');
//require_once(dirname(__FILE__).'/subject/subject_form.php');
$id = optional_param('id', 0, PARAM_INT); // course_module ID, or
$a = optional_param('a', 0, PARAM_INT);  // studentcp instance ID
$subjectid = optional_param('subjectid', 0, PARAM_INT);  // studentcp instance ID
//get current month and year.
$currentdate = usergetdate($currenttime);
$drl_month = $currentdate['mon'];
$drl_year = $currentdate['year'];
if ($id) {
    if (!$cm = get_coursemodule_from_id('studentcp', $id)) {
        error('Course Module ID was incorrect');
    }

    if (!$course = get_record('course', 'id', $cm->course)) {
        error('Course is misconfigured');
    }

    if (!$studentcp = get_record('studentcp', 'id', $cm->instance)) {
        error('Course module is incorrect');
    }
} else if ($a) {
    if (!$studentcp = get_record('studentcp', 'id', $a)) {
        error('Course module is incorrect');
    }
    if (!$course = get_record('course', 'id', $studentcp->course)) {
        error('Course is misconfigured');
    }
    if (!$cm = get_coursemodule_from_instance('studentcp', $studentcp->id, $course->id)) {
        error('Course Module ID was incorrect');
    }
} else {
    error('You must specify a course_module ID or an instance ID');
}

require_login($course, true, $cm);
if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
    print_error('badcontext');
}
require_capability('mod/studentcp:managesubject', $context);
if ($form = data_submitted()) {
    if ($form->submitbutton == 'OK') {


        $newsubject->id = $form->subjectid;
        //print_r($form);
        $newsubject->subjectcode = $form->subjectcode;
        $newsubject->name = $form->subjectname;
        $newsubject->categoryid = $form->category;
        $newsubject->credit = $form->subjectcredit;
        $newsubject->description = $form->description;
        if ($form->subjectid == 0) {
            if (validateSubject($newsubject)) {
                $newsubject->gradetable = $form->gradetable;
                $newsubject->gradedesc = $form->gradedesc;
                if (insert_record('studentcp_subject', $newsubject)) {
                    redirect("../subjectmanagement.php?id=$form->id", get_string('insertsuccess', 'studentcp'), 3);
                } else
                    redirect("../subjectmanagement.php?id=$form->id", get_string('insertfail', 'studentcp'), 3);
            } else
                redirect("../subjectmanagement.php?id=$form->id", get_string('invalidsubject', 'studentcp'), 3);
        }

        if ($subject = get_record('studentcp_subject', 'id', $form->subjectid)) {
            $newsubject->gradetable = $subject->gradetable;
            $newsubject->gradedesc = $subject->gradedesc;
            update_record('studentcp_subject', $newsubject);
            require_once($CFG->dirroot . '/lib/uploadlib.php');
            $um = new upload_manager('userfile', false, false, null, false, 0);
            if ($um->preprocess_files() and confirm_sesskey()) {
                $filename = $um->files['userfile']['tmp_name'];
                $text = my_file_get_contents($filename);
//                $markheader = $text[0];
                //unset($text[]);
                $count = 0;
                if ($newsubject->subjectcode != $text[0][1]) {
                    notify("Difference subject code!!!");
                    redirect("../subjectmanagement.php?id=$form->id", get_string('updatefail', 'studentcp'), 5);
                } else {
                    $semester = mktime(0, 0, 0, $text[1][1], 1, $text[2][1]);
                    if ($semester == 0)
                        $semester == mktime(0, 0, 0, $drl_month, 1, $drl_year);
                    foreach ($text as $studentgrade) {
                        if ($count++ > 3) {
                            if (!$user = get_record('user', 'username', addslashes($studentgrade[1]))) {
                                notify("user mapping error, could not find user with username \"$studentgrade[1]\"");
                            } else {
                                if (validateGrade($studentgrade, $newsubject->gradedesc)) {

                                    if ($grade = get_record('studentcp_grade', 'userid', $user->id, 'subjectid', $newsubject->id)) {
                                        $grade->gradedata = getGradeData($studentgrade);
                                        $grade->semester = $semester;
                                        update_record('studentcp_grade', $grade);
                                    } else {
                                        $grade->userid = $user->id;
                                        $grade->subjectid = $newsubject->id;
                                        $grade->gradedata = getGradeData($studentgrade);
                                        $grade->semster = $semester;
                                        insert_record('studentcp_grade', $grade);
                                    }
                                } else {
                                    notify("wrong grade format, could not add grade table with username \"$studentgrade[1]\"");
                                }
                            }
                        }
                    }
                }
            }
            redirect("../subjectmanagement.php?id=$form->id", get_string('updategradesuccess', 'studentcp'), 3);
        }
    } else if ($form->delete == 'Delete' && $form->confirmdelete == 1) {
        delete_records('studentcp_grade', 'subjectid', $form->subjectid);
        delete_records('studentcp_subject', 'id', $form->subjectid);
        redirect("../subjectmanagement.php?id=$cm->id", get_string('deleted', 'studentcp'), 1);
    }
    else
        redirect("../subjectmanagement.php?id=$cm->id", get_string('cancel', 'studentcp'), 1);
} else
    redirect("../subjectmanagement.php?id=$cm->id", get_string('cancel', 'studentcp'), 1);

//Tobe construct
function validateSubject($newsubject) {
    return true;
}

function validateGrade($studentgrade, $subjectDesc) {
    return count($studentgrade) - 3 == count(explode(";", $subjectDesc));
}

function getGradeData($studentgrade) {
    $string = '';
    if (count($studentgrade) - 3 == 1) {
        return preg_replace('/,/', '.', $studentgrade[3]);
    }
    for ($i = 3, $j = count($studentgrade) - 1; $i < $j; $i++) {
        $string = $string . $studentgrade[$i] . ';';
    }
    $string .= $studentgrade[count($studentgrade) - 1];
    return preg_replace('/,/', '.', $string);
}

//update_record($table, $dataobject);
?>
